package com.lightmusic.auth.security.details.clientdetails;

import com.lightmusic.common.result.Result;
import com.lightmusic.music.api.OAuthClientFeignClient;
import com.lightmusic.music.dto.AuthClientDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

/**
 * OAuth2 客户端信息
 * @author lzc
 */
@Service
@RequiredArgsConstructor
public class ClientDetailsServiceImpl implements ClientDetailsService {

    @Autowired
    private final OAuthClientFeignClient oAuthClientFeignClient;

    @Override
    @Cacheable(cacheNames = "auth", key = "'oauth-client:'+#clientId")
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        try {
            Result<AuthClientDTO> result = oAuthClientFeignClient.getOAuth2ClientById(clientId);
            if (Result.success().getCode().equals(result.getCode())) {
                AuthClientDTO authClientDTO = result.getData();
                BaseClientDetails clientDetails = new BaseClientDetails(
                        authClientDTO.getClientId(),
                        authClientDTO.getResourceIds(),
                        authClientDTO.getScope(),
                        authClientDTO.getAuthorizedGrantTypes(),
                        authClientDTO.getAuthorities(),
                        authClientDTO.getWebServerRedirectUri()
                );
                clientDetails.setClientSecret("");
                clientDetails.setAccessTokenValiditySeconds(authClientDTO.getAccessTokenValidity());
                clientDetails.setRefreshTokenValiditySeconds(authClientDTO.getRefreshTokenValidity());
                return clientDetails;
            } else {
                throw new NoSuchClientException("No client with requested id:" + clientId);
            }
        } catch (EmptyResultDataAccessException var4){
            throw new NoSuchClientException("No client with requested id:" + clientId);
        }

    }
}
